package com.klm.netty.codec;

import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class ProtobufDecoder extends ByteToMessageDecoder {
    private final MessageLite prototype;

    public ProtobufDecoder(MessageLite prototype) {
        this.prototype = prototype;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        try {
            // 确保有足够的数据可读
            if (in.readableBytes() < 4) {
                return;
            }

            // 标记当前读取位置
            in.markReaderIndex();
            
            // 读取消息长度
            int length = in.readInt();
            
            // 检查消息体是否完整
            if (in.readableBytes() < length) {
                in.resetReaderIndex();
                return;
            }

            // 读取消息体
            byte[] body = new byte[length];
            in.readBytes(body);

            // 解析消息
            MessageLite message = prototype.getParserForType().parseFrom(body);
            out.add(message);

            log.debug("Decoded message: {}, length: {}", message.getClass().getSimpleName(), length);
        } catch (Exception e) {
            log.error("Failed to decode message", e);
            throw e;
        }
    }
} 